<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查询系统</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/stock.css" rel="stylesheet">
    <link href="/css/stock-enhanced.css" rel="stylesheet">

    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/bootstrap-icons.css" rel="stylesheet">
    <!-- 添加Chart.js用于图表显示 -->
    <script src="/js/chart.js"></script>
    <!-- 添加Font Awesome图标 -->
    <link rel="stylesheet" href="/css/all.min.css">
    <style>
        /* 简化的基础样式 */
        html, body {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow-x: auto;
            background: #ffffff;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .main-container {
            background: #ffffff;
            margin: 20px;
            padding: 20px;
            min-height: calc(100% - 40px);
        }

        /* 顶部导航菜单样式 */
        .top-nav {
            background: #667eea;
            padding: 10px 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .nav-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .nav-links {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .nav-links button {
            background-color: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            border-radius: 4px;
            padding: 5px 10px;
            cursor: pointer;
        }

        .nav-links a {
            color: white;
            text-decoration: none;
            background: rgba(255, 255, 255, 0.2);
            padding: 5px 10px;
            border-radius: 4px;
        }

        .nav-links a:hover, .nav-links button:hover {
            background: rgba(255, 255, 255, 0.3);
            transition: background 0.3s;
        }

        /* 复盘数据表格样式 */
        .review-table-container {
            margin-bottom: 20px;
            overflow-x: auto;
        }

        .review-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        .review-table th, .review-table td {
            border: 1px solid #e0e0e0;
            padding: 8px 12px;
            text-align: left;
        }

        .review-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }

        .review-table tr:hover {
            background-color: #f9f9f9;
        }

        .positive {
            color: #dc3545; /* 红色表示上涨 */
        }

        .negative {
            color: #28a745; /* 绿色表示下跌 */
        }

        /* 标题区域简化 */
        .header-section {
            background: #667eea;
            color: white;
            padding: 15px;
            margin-bottom: 20px;
        }

        .header-title {
            font-size: 1.8rem;
            margin-bottom: 10px;
        }

        .header-subtitle {
            font-size: 1rem;
            margin-bottom: 15px;
        }

        .header-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .header-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 8px 15px;
            border-radius: 4px;
            text-decoration: none;
        }

        /* 统计面板样式简化 */
        .stats-panel {
            background: white;
            border: 1px solid #e0e0e0;
            padding: 15px;
            margin-bottom: 20px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }

        .stat-card {
            background: #f9f9f9;
            padding: 15px;
            border: 1px solid #e0e0e0;
            text-align: center;
        }

        .stat-number {
            font-size: 1.5rem;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 0.9rem;
            color: #666;
        }

        .chart-container {
            border: 1px solid #e0e0e0;
            padding: 15px;
            height: 300px;
            margin-bottom: 15px;
        }

        /* 控制面板简化 */
        .input-controls-section {
            background: white;
            border: 1px solid #e0e0e0;
            padding: 15px;
            margin-bottom: 20px;
        }

        .collapse-toggle {
            color: #667eea;
            cursor: pointer;
            text-decoration: underline;
        }

        .input-section {
            background: #f9f9f9;
            padding: 15px;
            border: 1px solid #e0e0e0;
            margin-bottom: 15px;
        }

        .form-control, .form-select {
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        .btn-primary {
            background: #667eea;
            border: none;
            padding: 8px 15px;
            color: white;
            border-radius: 4px;
        }

        /* 表格样式简化 */
        .table-responsive {
            border: 1px solid #e0e0e0;
            padding: 15px;
            margin-bottom: 20px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        .table th {
            background: #f0f0f0;
            padding: 8px;
            text-align: left;
            border: 1px solid #e0e0e0;
        }

        .table td {
            padding: 8px;
            border: 1px solid #e0e0e0;
        }

        .table tbody tr:hover {
            background-color: #f9f9f9;
        }

        /* 按钮和控件简化 */
        .badge {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.8rem;
        }

        .btn-sm {
            padding: 5px 10px;
            font-size: 0.8rem;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .main-container {
                margin: 10px;
                padding: 10px;
            }

            .stats-grid {
                grid-template-columns: 1fr 1fr;
            }

            .nav-content {
                flex-direction: column;
                gap: 10px;
            }

            .nav-links {
                flex-wrap: wrap;
                justify-content: center;
            }
        }

        /* 自动换行列样式 */
        .review-table .wrap-column {
            /* 设置最大宽度，超过则换行 */
            max-width: 480px;
            /* 允许文本正常换行 */
            white-space: normal;
            /* 长单词或URL自动拆分换行 */
            word-wrap: break-word;
            /* 内容溢出时隐藏并显示省略号（可选） */
            /* overflow: hidden;
            text-overflow: ellipsis; */
        }

        /* 自动换行列样式 */
        .review-table .wrap-column-b {
            /* 设置最大宽度，超过则换行 */
            max-width: 520px;
            /* 允许文本正常换行 */
            white-space: normal;
            /* 长单词或URL自动拆分换行 */
            word-wrap: break-word;
            /* 内容溢出时隐藏并显示省略号（可选） */
            /* overflow: hidden;
            text-overflow: ellipsis; */
        }

        /* 确保表格单元格也应用相同样式 */
        .review-table td.wrap-cell {
            max-width: 480px;
            white-space: normal;
            word-wrap: break-word;
            vertical-align: top; /* 顶部对齐，使多行文本更美观 */
        }

        .review-table th {
            font-size: 15px; /* 表头字体 */
        }

        .review-table td {
            font-size: 14px; /* 表格内容字体 */
        }

        /* 个股标记颜色样式 */
        .stock-yellow {
            color: #ffc107 !important;
            font-weight: bold;
        }
        .stock-red {
            color: #dc3545 !important;
            font-weight: bold;
        }
        .stock-green {
            color: green !important;
            font-weight: bold;
        }
        .stock-purple {
            color: #9c27b0 !important;
            font-weight: bold;
        }

        /* 日期选择器样式 */
        .date-picker-container {
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .date-picker-container .form-label {
            margin-bottom: 0;
            font-weight: 500;
        }

        #reviewDate {
            width: auto;
            padding: 6px 12px;
        }
    </style>
</head>
<body>
<!-- 顶部导航菜单 -->
<div class="top-nav">
    <div class="nav-content">
        <div class="nav-links">
            <button id="openAllLinks">
                <i class="fas fa-external-link-alt"></i> 全部打开
            </button>
            <a href="/gainian" target="_blank">
                <i class="fas fa-arrow-trend-up"></i> 概念资金
            </a>
            <a href="/stocksflow" target="_blank">
                <i class="fas fa-arrow-trend-up"></i> 个股资金
            </a>
            <a href="/analysis" target="_blank">
                <i class="fas fa-arrow-trend-up"></i> 数据分析
            </a>
            <a href="/limitup/search" target="_blank">
                <i class="fas fa-arrow-trend-up"></i> 涨停查询
            </a>
            <h4 class="m-0 fs-5 mb-n1"><i class="fas fa-history me-2"></i>市场复盘数据</h4>
            <label for="reviewDate" class="form-label mb-0 ms-3">选择日期:</label>
            <input type="date" class="form-control flex-grow-1" id="reviewDate" style="height: 32px;">
        </div>
    </div>
</div>

<!-- 复盘数据表格 -->
<div class="main-container">
    <div class="review-table-container">
        <div class="d-flex align-items-center gap-2 py-1">
            <!-- 合并为一个flex容器，减少整体垂直占用空间 -->
            <div class="date-picker-container flex-1 d-flex align-items-center gap-1">
                <span id="flowBoolres" class="text-danger ms-2" style="font-weight: 500;"></span>
            </div>
        </div>

        <table class="review-table">
            <thead>
            <tr>
                <th>日期</th>
                <th>总数</th>
                <th>上涨</th>
                <th>涨比</th>
                <th>下跌</th>
                <th>涨停</th>
                <th>跌停</th>
                <th>资金(亿)</th>
                <th>主力(亿)</th>
                <th>记录</th>
                <th class="wrap-column">
                    <div class="copy-buttons" style="margin-top:5px;">
                        概念
                        <button class="btn btn-xs btn-danger" onclick="copyRedConcepts()" title="复制最新标红概念">
                            <i class="fas fa-copy"></i> 复制重复
                        </button>
                        <button class="btn btn-xs btn-primary" onclick="copyAllConcepts()" title="复制最新所有概念">
                            <i class="fas fa-copy"></i> 复制全部
                        </button>
                        <button class="btn btn-xs btn-info" onclick="copyNonRedundantConcepts()" title="复制非重复出现的概念">
                            <i class="fas fa-copy"></i> 复制非重复
                        </button>
                    </div>
                </th> <!-- 添加wrap-column类 -->
                <th class="wrap-column-b">
                    <div class="copy-buttons" style="margin-top:5px;">
<!--                        个股-->
                        <button class="btn btn-sm btn-warning" onclick="copyYellowAndPurpleStocks()" title="查询出现">
                            <i class="fas fa-copy"></i> 查询
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="copyRedAndPurpleStocks()" title="前十天策略出现">
                            <i class="fas fa-copy"></i> 前十天策略
                        </button>
                        <button class="btn btn-sm btn-primary" onclick="copyPurpleStocks()" title="前十天策略+查询出现">
                            <i class="fas fa-copy"></i> 查询+策略
                        </button>
                        <button class="btn btn-sm btn-secondary" onclick="copyNonColoredStocks()" title="复制非黄红紫的个股">
                            <i class="fas fa-copy"></i> 非查非策略
                        </button>
                        <button class="btn btn-sm btn-secondary" onclick="copyAllStock()" title="复制所有个股">
                            <i class="fas fa-copy"></i> 复制所有
                        </button>
                    </div>
                </th> <!-- 添加wrap-column类 -->
            </tr>
            </thead>
            <tbody id="reviewTableBody">
            <!-- 数据将通过JavaScript动态填充 -->
            <tr>
                <td colspan="12" class="text-center">加载中...</td>
            </tr>
            </tbody>
        </table>
    </div>

    <!-- 折叠控制区域 -->
    <div class="input-controls-section">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div></div>
            <textarea class="form-control" id="allOptional" rows="3" maxlength="10000" style="background-color: #f8f9fa;" onchange="checkallOptional()" placeholder="自选"></textarea>
            <a class="collapse-toggle" data-bs-toggle="collapse" href="#inputControlsCollapse" role="button"
               aria-expanded="true" aria-controls="inputControlsCollapse">
                <span class="collapse-text">收起</span>
                <span class="collapse-icon">▼</span>
            </a>
        </div>

        <div class="collapse show" id="inputControlsCollapse">
            <div class="row">
                <div class="col-md-4">
                    <div class="input-section">
                        <h6 class="mb-3">
                            <i class="fas fa-star me-2"></i>重点关注设置
                            <span class="badge bg-secondary" id="saveFocus" onclick="updateSys()">保存关注</span>
                            <span class="badge bg-secondary" id="redu" onclick="openReduIwencai()">打开热榜</span>
                            <span class="badge bg-secondary" id="todayzt" onclick="openIwencaiKey('今日涨停的股票，热度排行榜，昨天热度排行排名')">今日涨停</span>
                        </h6>
                        <div class="input-group mb-3">
                            <textarea class="form-control" id="focusGainian" rows="2" placeholder="重点概念"></textarea>
                        </div>

                        <div class="input-group mb-3">
                            <textarea class="form-control" id="focusStocks" rows="2" onchange="checkfocusStocks();" placeholder="输入股票代码，每行一个"></textarea>
                            <div class="history-dropdown" id="focusStocksHistory"></div>
                        </div>

                        <div class="row">
                            <div class="col-4">
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" id="showOnlyGEM">
                                    <label class="form-check-label" for="showOnlyGEM">创业板</label>
                                </div>
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" id="showOnlyKCB">
                                    <label class="form-check-label" for="showOnlyKCB">科创板</label>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" id="showOnlyMain">
                                    <label class="form-check-label" for="showOnlyMain">主板</label>
                                </div>
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" id="showOnlyBJ">
                                    <label class="form-check-label" for="showOnlyBJ">北交所</label>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" id="showOnlyST">
                                    <label class="form-check-label" for="showOnlyST">ST股票</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="input-section">
                        <h6 class="mb-3">
                            <i class="fas fa-search me-2"></i>智能搜索
                            <span class="badge bg-secondary" id="tongpei" onclick="processSpecialString()">去掉通配</span>
                            <span class="badge bg-secondary" id="reflesh" onclick="location.reload()">重置刷新</span>
                            <span class="badge bg-secondary" id="openIwencai" onclick="openIwencai()">打开问财</span>
                        </h6>
                        <div class="input-group mb-3">
                            <textarea class="form-control" id="iwencaiKeyword" rows="3"
                                      placeholder="输入关键词进行智能搜索"></textarea>
                            <div class="history-dropdown" id="iwencaiHistory"></div>
                        </div>
                        <div class="input-group mb-3">
                            <label class="input-group-text" for="checkInterval">
                                <i class="fas fa-clock"></i>
                            </label>
                            <input type="number" class="form-control" id="checkInterval" placeholder="检测间隔（秒）"
                                   value="300">
                            <button class="btn btn-primary" type="button" id="monitorBtn" onclick="toggleMonitoring()">
                                <i class="fas fa-play me-1"></i>开始监控
                            </button>
                        </div>

                        <div class="row mb-2">
                            <div class="col-6">
                                <div class="row">
                                    <div class="col-6">
                                        <input type="time" class="form-control form-control-sm" id="morningStart" value="09:20">
                                    </div>
                                    <div class="col-6">
                                        <input type="time" class="form-control form-control-sm" id="morningEnd" value="11:35">
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="row">
                                    <div class="col-6">
                                        <input type="time" class="form-control form-control-sm" id="afternoonStart" value="12:55">
                                    </div>
                                    <div class="col-6">
                                        <input type="time" class="form-control form-control-sm" id="afternoonEnd" value="15:10">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="enableTimeControl" checked>
                                <label class="form-check-label small" for="enableTimeControl">
                                    启用时间段控制
                                </label>
                            </div>
                            <div class="alert alert-info mb-0" role="alert" id="monitorStatus" style="flex: 1; margin-left: 15px; padding: 5px;">
                                <small>监控状态：<span class="badge bg-secondary">已关闭</span></small>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="input-section">
                        <h6 class="mb-3">
                            <i class="fas fa-tags me-2"></i>概念监控
                            <span class="badge bg-secondary" id="openGainianIwencai" onclick="openGainianIwencai()">打开问财</span>
                        </h6>
                        <div class="input-group mb-3">
                            <textarea class="form-control" id="gainianKeyword" rows="2"
                                      placeholder="输入概念提示词"></textarea>
                            <div class="history-dropdown" id="gainianHistory"></div>
                        </div>
                        <div class="input-group mb-3">
                            <label class="input-group-text" for="gainianInterval">
                                <i class="fas fa-stopwatch"></i>
                            </label>
                            <input type="number" class="form-control" id="gainianInterval" placeholder="检测间隔（秒）"
                                   value="300">
                            <button class="btn btn-primary" type="button" id="gainianMonitorBtn"
                                    onclick="toggleGainianMonitoring()">
                                <i class="fas fa-play me-1"></i>开始监控
                            </button>
                        </div>

                        <div class="row">
                            <div class="col-6">
                                <div class="form-check form-switch mb-1">
                                    <input class="form-check-input" type="checkbox" id="autoRefreshConcepts" checked>
                                    <label class="form-check-label small" for="autoRefreshConcepts">自动刷新概念</label>
                                </div>
                                <div class="form-check form-switch mb-1">
                                    <input class="form-check-input" type="checkbox" id="notifyOnNewConcept">
                                    <label class="form-check-label small" for="notifyOnNewConcept">新概念提醒</label>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" id="followMainMonitor" checked>
                                    <label class="form-check-label small" for="followMainMonitor">监控时间段</label>
                                </div>
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" id="enableConceptFilter">
                                    <label class="form-check-label small" for="enableConceptFilter">启用概念筛选</label>
                                </div>
                            </div>
                        </div>

                        <div class="alert alert-info mb-0" role="alert" id="gainianMonitorStatus" style="padding: 5px;">
                            <small>概念监控状态：<span class="badge bg-secondary">已关闭</span></small>
                        </div>
                    </div>
                </div>

                <div class="col-md-12">
                    <div class="input-section">
                        <div class="input-group">
                            <textarea class="form-control" id="hotGainian" rows="3" readonly
                                      style="background-color: #f8f9fa;" placeholder="热门概念将在这里显示"></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-responsive" id="tableContainer">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div class="d-flex align-items-center gap-2">
                <button class="btn btn-sm btn-outline-secondary" id="clearSortBtn" style="display: none;">
                    <i class="fas fa-undo me-1"></i>恢复默认排序
                </button>
                <div class="btn-group" role="group">
                    <button class="btn btn-outline-warning btn-sm" id="copyType0Btn" style="display: none;">
                        复制所有股票
                    </button>
                    <button class="btn btn-outline-warning btn-sm" id="copyType1Btn" style="display: none;">
                        复制重点关注股票
                    </button>
                    <button class="btn btn-outline-success btn-sm" id="copyType2Btn" style="display: none;">
                        <i class="fas fa-plus-circle me-1"></i>复制新出现股票
                    </button>
                    <button class="btn btn-outline-primary btn-sm" id="copyType3Btn" style="display: none;">
                        <i class="fas fa-water me-1"></i>复制洗盘股票
                    </button>
                    <button class="btn btn-outline-danger btn-sm" id="copyType4Btn" style="display: none;">
                        <i class="fas fa-link me-1"></i>复制连续股票
                    </button>
                    <button class="btn btn-outline-info btn-sm" id="copyGainianBtn" style="display: none;">
                        <i class="fas fa-tags me-1"></i>复制概念股票
                    </button>
                </div>
            </div>
            <div class="text-muted small" id="sortStatus">
                <i class="fas fa-sort me-1"></i>按股票类型排序
            </div>
        </div>
        <table class="table table-hover">
            <thead>
            <tr>
                <th><i class="fas fa-hashtag me-1"></i>代码</th>
                <th><i class="fas fa-building me-1"></i>名称</th>
                <th class="sortable" data-sort="price">
                    <i class="fas fa-dollar-sign me-1"></i>最新价 <span class="sort-icon">⇅</span>
                </th>
                <th class="sortable" data-sort="changePercent">
                    <i class="fas fa-percentage me-1"></i>涨跌幅 <span class="sort-icon">⇅</span>
                </th>
                <th><i class="fas fa-play me-1"></i>今开</th>
                <th><i class="fas fa-arrow-up me-1"></i>最高</th>
                <th><i class="fas fa-arrow-down me-1"></i>最低</th>
                <th class="sortable gainian-column" data-sort="gainian">
                    <i class="fas fa-layer-group me-1"></i>所属热门板块 <span class="sort-icon">⇅</span>
                    <small class="text-muted d-block"
                           style="font-size: 10px; font-weight: normal;">(点击板块名复制)</small>
                </th>
                <th class="sortable" data-sort="flows">
                    <i class="fas fa-water me-1"></i>主力流入 <span class="sort-icon">⇅</span>
                </th>
                <th class="sortable" data-sort="hots">
                    <i class="fas fa-fire me-1"></i>热度榜 <span class="sort-icon">⇅</span>
                </th>
            </tr>
            </thead>
            <tbody id="stockTableBody">
            </tbody>
        </table>

        <!-- 全屏模式下的退出按钮 -->
        <button class="btn btn-danger" id="exitFullscreenBtn" style="display: none;">
            <i class="fas fa-times me-2"></i>退出全屏
        </button>
    </div>

    <div class="stats-panel">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="mb-0">
                <i class="fas fa-chart-pie me-2"></i>市场概览与板块分布
            </h4>
            <a class="collapse-toggle" data-bs-toggle="collapse" href="#statsCollapse" role="button"
               aria-expanded="true" aria-controls="statsCollapse">
                <span class="collapse-icon">▼</span>
                <span class="collapse-text">收起</span>
            </a>
        </div>

        <div class="collapse" id="statsCollapse">
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-number" id="totalStockCount">0</div>
                    <div class="stat-label">
                        <i class="fas fa-list me-1"></i>总股票数
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="matchStockCount">0</div>
                    <div class="stat-label">
                        <i class="fas fa-filter me-1"></i>匹配数量
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="focusStockCount">0</div>
                    <div class="stat-label">
                        重点关注
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="newStockCount">0</div>
                    <div class="stat-label">
                        <i class="fas fa-plus-circle me-1"></i>新出现
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="chart-container">
                        <canvas id="sectorChart"></canvas>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="chart-container">
                        <canvas id="typeChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script>
    // 导航链接打开功能
    document.getElementById('openAllLinks').addEventListener('click', function() {
        // 获取所有导航链接
        const links = document.querySelectorAll('.nav-links a[target="_blank"]');

        // 遍历并打开每个链接
        links.forEach(link => {
            window.open(link.href, '_blank');
        });
    });

    // 复制最新一天所有的概念（已剔除[]内容）
    function copyAllStock() {
        // 获取最新一天（第一行）的概念单元格

        const firstRow = document.querySelector('#reviewTableBody tr:first-child');
        if (!firstRow) {
            alert('没有找到复盘数据');
            return;
        }
        const stockCell = firstRow.querySelector('td:nth-child(12)');
        // const conceptCell = firstRow.querySelector('td:nth-child(12)');
        if (!stockCell) {
            alert('没有找到个股数据');
            return;
        }

        // 获取原始概念文本
        const originalText = stockCell.textContent.trim();
        if (!originalText || originalText === '-') {
            alert('没有个股数据');
            return;
        }

        // 处理概念，去除[]及其中的数字
        const concepts = extractConcepts(originalText);

        // 复制到剪贴板
        const textToCopy = concepts.join(',');
        const copyCount = concepts.length;
        copyToClipboard(textToCopy);
        showCopyNotification(`所有个股已复制${copyCount}个到剪贴板`);

        // navigator.clipboard.writeText(textToCopy).then(() => {
        //     showCopyNotification(`所有概念已复制${copyCount}个到剪贴板`);
        // }).catch(err => {
        //     console.error('复制失败:', err);
        //     alert('复制失败，请手动复制');
        // });
    }

    // 复制黄色(存在于searchtr中)和紫色(同时存在于两者中)的个股
    function copyYellowAndPurpleStocks() {
        // 获取最新一天（第一行）的个股单元格
        const firstRow = document.querySelector('#reviewTableBody tr:first-child');
        if (!firstRow) {
            alert('没有找到复盘数据');
            return;
        }

        const stockCell = firstRow.querySelector('td:nth-child(12)');
        if (!stockCell) {
            alert('没有找到个股数据');
            return;
        }

        // 获取所有黄色和紫色的个股元素
        const targetStocks = stockCell.querySelectorAll('.stock-yellow, .stock-purple');
        if (targetStocks.length === 0) {
            alert('没有找到黄色或紫色的个股');
            return;
        }

        // 提取并处理个股，去除[]及其中的数字
        const stocks = Array.from(targetStocks)
            .map(span => span.textContent.trim())
            .map(stock => stock.replace(/\[\d+\]/g, '').trim());

        // 复制到剪贴板
        const textToCopy = stocks.join(',');
        const copyCount = stocks.length;

        copyToClipboard(textToCopy);
        showCopyNotification(`黄色和紫色个股已复制${copyCount}个到剪贴板`);

        // navigator.clipboard.writeText(textToCopy).then(() => {
        //     showCopyNotification(`黄色和紫色个股已复制${copyCount}个到剪贴板`);
        // }).catch(err => {
        //     console.error('复制失败:', err);
        //     alert('复制失败，请手动复制');
        // });
    }

    // 复制红色(存在于第二行中)和紫色(同时存在于两者中)的个股
    function copyRedAndPurpleStocks() {
        // 获取最新一天（第一行）的个股单元格
        const firstRow = document.querySelector('#reviewTableBody tr:first-child');
        if (!firstRow) {
            alert('没有找到复盘数据');
            return;
        }

        const stockCell = firstRow.querySelector('td:nth-child(12)');
        if (!stockCell) {
            alert('没有找到个股数据');
            return;
        }

        // 获取所有红色和紫色的个股元素
        const targetStocks = stockCell.querySelectorAll('.stock-red, .stock-purple');
        if (targetStocks.length === 0) {
            alert('没有找到红色或紫色的个股');
            return;
        }

        // 提取并处理个股，去除[]及其中的数字
        const stocks = Array.from(targetStocks)
            .map(span => span.textContent.trim())
            .map(stock => stock.replace(/\[\d+\]/g, '').trim());

        // 复制到剪贴板
        const textToCopy = stocks.join(',');
        const copyCount = stocks.length;

        copyToClipboard(textToCopy);
        showCopyNotification(`红色和紫色个股已复制${copyCount}个到剪贴板`);

        // navigator.clipboard.writeText(textToCopy).then(() => {
        //     showCopyNotification(`红色和紫色个股已复制${copyCount}个到剪贴板`);
        // }).catch(err => {
        //     console.error('复制失败:', err);
        //     alert('复制失败，请手动复制');
        // });
    }

    // 仅复制紫色(同时存在于两者中)的个股
    function copyPurpleStocks() {
        // 获取最新一天（第一行）的个股单元格
        const firstRow = document.querySelector('#reviewTableBody tr:first-child');
        if (!firstRow) {
            alert('没有找到复盘数据');
            return;
        }

        const stockCell = firstRow.querySelector('td:nth-child(12)');
        if (!stockCell) {
            alert('没有找到个股数据');
            return;
        }

        // 获取所有紫色的个股元素
        const purpleStocks = stockCell.querySelectorAll('.stock-purple');
        if (purpleStocks.length === 0) {
            alert('没有找到紫色的个股');
            return;
        }

        // 提取并处理个股，去除[]及其中的数字
        const stocks = Array.from(purpleStocks)
            .map(span => span.textContent.trim())
            .map(stock => stock.replace(/\[\d+\]/g, '').trim());

        // 复制到剪贴板
        const textToCopy = stocks.join(',');
        const copyCount = stocks.length;

        copyToClipboard(textToCopy);
        showCopyNotification(`紫色个股已复制${copyCount}个到剪贴板`);

        // navigator.clipboard.writeText(textToCopy).then(() => {
        //     showCopyNotification(`紫色个股已复制${copyCount}个到剪贴板`);
        // }).catch(err => {
        //     console.error('复制失败:', err);
        //     alert('复制失败，请手动复制');
        // });
    }

    // 复制不是黄红紫的个股
    function copyNonColoredStocks() {
        // 获取最新一天（第一行）的个股单元格
        const firstRow = document.querySelector('#reviewTableBody tr:first-child');
        if (!firstRow) {
            alert('没有找到复盘数据');
            return;
        }

        const stockCell = firstRow.querySelector('td:nth-child(12)');
        if (!stockCell) {
            alert('没有找到个股数据');
            return;
        }

        // 获取所有个股元素（包括文本节点）
        const allStockElements = [];
        stockCell.childNodes.forEach(node => {
            if (node.nodeType === Node.TEXT_NODE) {
                // 处理文本节点中的股票代码
                const text = node.textContent.trim();
                if (text) {
                    text.split(',').forEach(stock => {
                        if (stock.trim()) {
                            allStockElements.push({
                                text: stock.trim(),
                                isColored: false
                            });
                        }
                    });
                }
            } else if (node.nodeType === Node.ELEMENT_NODE &&
                !node.classList.contains('stock-yellow') &&
                !node.classList.contains('stock-red') &&
                !node.classList.contains('stock-purple')) {
                // 处理非黄红紫的元素
                allStockElements.push({
                    text: node.textContent.trim(),
                    isColored: false
                });
            }
        });

        // 提取并处理非黄红紫的个股，去除[]及其中的数字
        const stocks = allStockElements
            .map(item => item.text)
            .map(stock => stock.replace(/\[\d+\]/g, '').trim())
            .filter(stock => stock); // 过滤空值

        if (stocks.length === 0) {
            alert('没有找到非黄红紫的个股');
            return;
        }

        // 复制到剪贴板
        const textToCopy = stocks.join(',');
        const copyCount = stocks.length;

        copyToClipboard(textToCopy);
        showCopyNotification(`非黄红紫个股已复制${copyCount}个到剪贴板`);

        // navigator.clipboard.writeText(textToCopy).then(() => {
        //     showCopyNotification(`非黄红紫个股已复制${copyCount}个到剪贴板`);
        // }).catch(err => {
        //     console.error('复制失败:', err);
        //     alert('复制失败，请手动复制');
        // });
    }

    // 处理概念字符串，提取纯概念名称（去除[]及其中的数字）
    function extractConcepts(conceptStr) {
        if (!conceptStr || conceptStr === '-') return [];

        // 分割概念并去除[]及其中的数字
        return conceptStr.split(',')
            .map(concept => concept.replace(/\[\d+\]/g, '').trim())
            .filter(concept => concept); // 过滤空值
    }

    // 处理个股字符串，提取纯股票代码（去除[]及其中的数字）
    function extractStocks(stockStr) {
        if (!stockStr || stockStr === '-') return [];

        // 分割个股并去除[]及其中的数字
        return stockStr.split(',')
            .map(stock => stock.replace(/\[\d+\]/g, '').trim())
            .filter(stock => stock); // 过滤空值
    }

    // 复制最新一天标红的概念（已剔除[]内容）
    function copyRedConcepts() {
        // 获取最新一天（第一行）的概念单元格
        const firstRow = document.querySelector('#reviewTableBody tr:first-child');
        if (!firstRow) {
            alert('没有找到复盘数据');
            return;
        }

        const conceptCell = firstRow.querySelector('td:nth-child(11)');
        if (!conceptCell) {
            alert('没有找到概念数据');
            return;
        }

        // 获取所有标红的概念元素
        const redConcepts = conceptCell.querySelectorAll('span[style*="color: #dc3545"]');
        if (redConcepts.length === 0) {
            alert('没有标红的概念');
            return;
        }

        // 提取并处理标红的概念
        const concepts = Array.from(redConcepts)
            .map(span => span.textContent.trim())
            .map(concept => concept.replace(/\[\d+\]/g, '').trim());

        // 复制到剪贴板
        const textToCopy = concepts.join(',');
        const copyCount = concepts.length;
        copyToClipboard(textToCopy);
        showCopyNotification(`标红概念已复制${copyCount}个到剪贴板`);

        // navigator.clipboard.writeText(textToCopy).then(() => {
        //     showCopyNotification(`标红概念已复制${copyCount}个到剪贴板`);
        // }).catch(err => {
        //     console.error('复制失败:', err);
        //     alert('复制失败，请手动复制');
        // });
    }

    // 复制最新一天所有的概念（已剔除[]内容）
    function copyAllConcepts() {
        // 获取最新一天（第一行）的概念单元格
        const firstRow = document.querySelector('#reviewTableBody tr:first-child');
        if (!firstRow) {
            alert('没有找到复盘数据');
            return;
        }

        const conceptCell = firstRow.querySelector('td:nth-child(11)');
        if (!conceptCell) {
            alert('没有找到概念数据');
            return;
        }

        // 获取原始概念文本
        const originalText = conceptCell.textContent.trim();
        if (!originalText || originalText === '-') {
            alert('没有概念数据');
            return;
        }

        // 处理概念，去除[]及其中的数字
        const concepts = extractConcepts(originalText);

        // 复制到剪贴板
        const textToCopy = concepts.join(',');
        const copyCount = concepts.length;
        copyToClipboard(textToCopy);
        showCopyNotification(`所有概念已复制${copyCount}个到剪贴板`);

        // navigator.clipboard.writeText(textToCopy).then(() => {
        //     showCopyNotification(`所有概念已复制${copyCount}个到剪贴板`);
        // }).catch(err => {
        //     console.error('复制失败:', err);
        //     alert('复制失败，请手动复制');
        // });
    }

    // 复制不是重复出现的概念（仅在最新一天出现）
    function copyNonRedundantConcepts() {
        // 获取最新一天（第一行）和第二天（第二行）的概念单元格
        const firstRow = document.querySelector('#reviewTableBody tr:first-child');
        const secondRow = document.querySelector('#reviewTableBody tr:nth-child(2)');

        if (!firstRow) {
            alert('没有找到复盘数据');
            return;
        }

        const firstRowConceptCell = firstRow.querySelector('td:nth-child(11)');
        if (!firstRowConceptCell) {
            alert('没有找到概念数据');
            return;
        }

        // 获取最新一天的所有概念
        const firstRowOriginalText = firstRowConceptCell.textContent.trim();
        if (!firstRowOriginalText || firstRowOriginalText === '-') {
            alert('没有概念数据');
            return;
        }
        const allFirstRowConcepts = extractConcepts(firstRowOriginalText);

        // 获取第二天的所有概念（如果存在）
        let secondRowConcepts = [];
        if (secondRow) {
            const secondRowConceptCell = secondRow.querySelector('td:nth-child(11)');
            if (secondRowConceptCell) {
                const secondRowOriginalText = secondRowConceptCell.textContent.trim();
                if (secondRowOriginalText && secondRowOriginalText !== '-') {
                    secondRowConcepts = extractConcepts(secondRowOriginalText);
                }
            }
        }

        // 找出仅在最新一天出现的概念（非重复概念）
        const nonRedundantConcepts = allFirstRowConcepts.filter(concept =>
            !secondRowConcepts.includes(concept)
        );

        if (nonRedundantConcepts.length === 0) {
            alert('没有找到非重复出现的概念');
            return;
        }

        // 复制到剪贴板
        const textToCopy = nonRedundantConcepts.join(',');
        const copyCount = nonRedundantConcepts.length;
        copyToClipboard(textToCopy);
        showCopyNotification(`非重复概念已复制${copyCount}个到剪贴板`);

        // navigator.clipboard.writeText(textToCopy).then(() => {
        //     showCopyNotification(`非重复概念已复制${copyCount}个到剪贴板`);
        // }).catch(err => {
        //     console.error('复制失败:', err);
        //     alert('复制失败，请手动复制');
        // });
    }

    // 显示复制成功的通知
    function showCopyNotification(message) {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.style.position = 'fixed';
        notification.style.bottom = '20px';
        notification.style.right = '20px';
        notification.style.backgroundColor = 'rgba(0, 128, 0, 0.8)';
        notification.style.color = 'white';
        notification.style.padding = '10px 20px';
        notification.style.borderRadius = '4px';
        notification.style.zIndex = '9999';
        notification.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.2)';
        notification.textContent = message;

        // 添加到页面
        document.body.appendChild(notification);

        // 3秒后移除通知
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transition = 'opacity 0.5s';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 500);
        }, 3000);
    }

    // 处理复盘数据并显示为表格，添加概念高亮和个股标记功能
    function renderReviewTable(data) {
        const tableBody = document.getElementById('reviewTableBody');
        tableBody.innerHTML = ''; // 清空表格

        if (!data || data.trim() === '') {
            tableBody.innerHTML = '<tr><td colspan="12" class="text-center">无复盘数据</td></tr>';
            return;
        }

        // 按行分割数据
        const rows = data.split('\n');

        // 去重处理并保留原始顺序
        const uniqueRows = [];
        const seen = new Set();
        rows.forEach(row => {
            if (row.trim() !== '' && !seen.has(row)) {
                seen.add(row);
                uniqueRows.push(row);
            }
        });

        // 先解析所有行数据，以便后续比较
        const parsedRows = [];
        uniqueRows.forEach(row => {
            if (row.trim() === '') return;

            // 解析每行数据
            const parts = row.split(';');
            const rowData = {};

            parts.forEach(part => {
                const [key, value] = part.split('#').map(item => item.trim());
                if (key && value) {
                    // 处理键名，移除特殊字符并标准化
                    const cleanKey = key.replace(/[：:]/, '').trim();
                    rowData[cleanKey] = value;
                }
            });

            // 提取概念列表（去除数字标记）
            rowData.conceptsList = extractConcepts(rowData['概念']);
            // 提取个股列表（去除数字标记）
            rowData.stocksList = extractStocks(rowData['个股']);
            parsedRows.push(rowData);
        });

        // 处理searchtr数据，转换为股票代码数组
        const searchtrStocks = searchtr ? searchtr.split(',').map(stock => stock.trim()) : [];

        // 遍历解析后的行数据并创建表格行
        parsedRows.forEach((rowData, index) => {
            // 创建表格行
            const tr = document.createElement('tr');

            // 格式化资金数据并添加颜色类
            const formatMoney = (value) => {
                const num = parseFloat(value);
                return num >= 0 ?
                    `<span class="positive">${num}</span>` :
                    `<span class="negative">${num}</span>`;
            };

            const formatTimeMD = (timeStr) => {
                if (!timeStr) return '-';
                const date = new Date(timeStr);
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${month}-${day} ${hours}:${minutes}`;
            };

            // 格式化涨比数据并添加颜色类
            const formatUP = (num) => {
                return num >= 40 ?
                    `<span class="positive">${num}</span>` :
                    `<span class="negative">${num}</span>`;
            };

            // 处理概念显示和高亮
            let conceptsHtml = '-';
            if (rowData['概念'] && rowData['概念'] !== '-') {
                // 拆分概念
                const concepts = rowData['概念'].split(',');

                // 获取第二天数据（如果存在）
                const nextDayData = index === 0 && parsedRows.length > 1 ? parsedRows[1] : null;
                // 获取前一天数据（如果存在）
                const prevDayData = index === 1 ? parsedRows[0] : null;

                // 构建概念HTML
                conceptsHtml = concepts.map(concept => {
                    // 提取纯概念名称（去除数字标记）
                    const pureConcept = concept.replace(/\[\d+\]/g, '').trim();

                    // 检查当前概念是否存在于第二天（适用于最新一天）
                    const isInNextDay = nextDayData && nextDayData.conceptsList.includes(pureConcept);

                    // 检查当前概念是否存在于最新一天（适用于第二天）
                    const isInLatestDay = prevDayData && prevDayData.conceptsList.includes(pureConcept);

                    // 最新一天（第一行）中存在于第二天的概念标记为红色
                    if (index === 0 && isInNextDay) {
                        return `<span style="color: #dc3545 !important; font-weight: bold;">${concept}</span>`;
                    }
                    // 第二天（第二行）中存在于最新一天的概念标记为黄色
                    else if (index === 1 && isInLatestDay) {
                        return `<span style="color: #ffc107 !important; font-weight: bold;">${concept}</span>`;
                    }

                    return concept;
                }).join(',');
            }

            // 处理个股显示和颜色标记
            let stocksHtml = '-';
            if (rowData['个股'] && rowData['个股'] !== '-') {
                // 拆分个股
                const stocks = rowData['个股'].split(',');

                // 对于第一行数据，需要进行颜色标记
                if (index === 0) {
                    // 获取第二行的个股数据（如果存在）
                    const startIndex = 1; // 从第2行开始（跳过第一行）
                    const endIndex = parsedRows.length > 10 ? 11 : parsedRows.length; // 结束索引：10行则到11（前闭后开），否则到末尾
                    const targetRows = parsedRows.length > 1 ? parsedRows.slice(startIndex, endIndex) : [];

                    // 合并目标行的所有股票列表（处理可能的undefined）
                    const targetStocks = targetRows.flatMap(row => row.stocksList || []);

                    stocksHtml = stocks.map(stock => {
                        // 提取纯股票代码（去除数字标记）
                        const pureStock = stock.replace(/\[\d+\]/g, '').trim();

                        // 检查是否存在于searchtr中
                        const inSearchtr = searchtrStocks.includes(pureStock);
                        // 检查是否存在于目标行数据中（最近10行或最大长度行）
                        const inTargetRows = targetStocks.includes(pureStock);
                        // console.log("targetStocks=="+targetStocks)
                        // console.log("focus=="+focus)
                        const inFlowRows = focus.includes(pureStock);

                        // 应用颜色标记
                        if (inFlowRows) {
                            return `<span class="stock-green">${stock}</span>`;
                        }else if (inSearchtr && inTargetRows) {
                            return `<span class="stock-purple">${stock}</span>`;
                        } else if (inSearchtr) {
                            return `<span class="stock-yellow">${stock}</span>`;
                        } else if (inTargetRows) {
                            return `<span class="stock-red">${stock}</span>`;
                        }
                        return stock;
                    }).join(',');
                } else {
                    // 非第一行数据直接显示
                    stocksHtml = stocks.join(',');
                }
            }

            // 添加表格单元格
            tr.innerHTML = `
            <td>${rowData['日期'] || '-'}</td>
            <td>${rowData['总数'] || '-'}</td>
            <td>${rowData['上涨'] || '-'}</td>
            <td>${rowData['涨比'] ? formatUP(rowData['涨比']) : '-'}%</td>
            <td>${rowData['下跌'] || '-'}</td>
            <td>${rowData['涨停'] || '-'}</td>
            <td>${rowData['跌停'] || '-'}</td>
            <td>${rowData['总资金'] ? formatMoney(rowData['总资金']) : '-'}</td>
            <td>${rowData['主力资金'] ? formatMoney(rowData['主力资金']) : '-'}</td>
            <td>${rowData['时间'] ? formatTimeMD(rowData['时间']) : '-'}</td>
            <td class="wrap-cell">${conceptsHtml}</td>
            <td class="wrap-cell">${stocksHtml}</td>
        `;

            tableBody.appendChild(tr);
        });
    }

    // 图表实例
    let sectorChart = null;
    let typeChart = null;
    let searchtr = null;
    let focusBoll = null;
    let focus = null;

    // 根据日期加载配置数据
    function loadConfigByDate(date) {
        // 显示加载状态
        const tableBody = document.getElementById('reviewTableBody');
        tableBody.innerHTML = '<tr><td colspan="12" class="text-center">加载中...</td></tr>';

        const params = date ? { startDate: date } : {};

        $.ajax({
            url: '/api/iwencai/config',
            method: 'GET',
            data: params,
            success: function (response) {
                // 设置默认值
                let allOptional = response.focus+","+response.allOptional;
                $('#focusStocks').val(allOptional.split(',').join('\n'));
                $('#focusGainian').val(response.focusGainian || '');
                focus = allOptional;
                searchtr = response.searchtr;
                focusBoll = response.focusBoll;
                $('#allOptional').val(response.allOptional || '');
                $('#iwencaiKeyword').val(response.searchKeyword || '');
                $('#gainianKeyword').val(response.gainianKeyword || '');
                $('#checkInterval').val(response.searchInterval || 300);
                $('#gainianInterval').val(response.gainianInterval || 300);
                // console.log("searchtr==="+searchtr);
                // 处理并渲染复盘数据
                if (response.reviewCon) {
                    renderReviewTable(response.reviewCon);
                }

                // 加载时间段配置
                $('#morningStart').val(response.morningStart || '09:18');
                $('#morningEnd').val(response.morningEnd || '11:35');
                $('#afternoonStart').val(response.afternoonStart || '12:55');
                $('#afternoonEnd').val(response.afternoonEnd || '15:10');
                $('#enableTimeControl').prop('checked', response.enableTimeControl !== false);

                // 初始化时间状态显示
                updateTimeStatus();
                // console.log('focusBoll==='+focusBoll);
                // $('#flowBoolres').text(focusBoll || '');
                $('#flowBoolres').html(focusBoll || '');
            },
            error: function (error) {
                console.error('获取默认配置失败:', error);
                // 初始化时间状态显示
                updateTimeStatus();
                // 显示无数据状态
                renderReviewTable('');
            }
        });
    }

    // 页面加载完成后获取默认配置
    $(document).ready(function () {
        // 初始化图表
        initCharts();

        // 初始化统计面板折叠功能
        initStatsCollapse();

        // 初始化控制面板折叠功能
        initControlsCollapse();

        // 初始化全屏功能
        initFullscreenFeature();

        // 初始化日期选择器
        const today = new Date().toISOString().split('T')[0];
        $('#reviewDate').val(today);

        // 封装加载数据的函数
        function loadSelectedDateData() {
            const selectedDate = $('#reviewDate').val();
            if (selectedDate) {
                loadConfigByDate(selectedDate);
            } else {
                alert('请选择日期');
            }
        }

        // 添加日期选择器变化事件，实现自动加载
        $('#reviewDate').on('change', loadSelectedDateData);

        // 日期选择框回车事件
        $('#reviewDate').on('keypress', function(e) {
            if (e.which === 13) { // 回车键
                loadSelectedDateData();
            }
        });

        // 使用默认日期（今天）加载数据
        loadConfigByDate(today);

        // 启动时间状态更新定时器
        setInterval(updateTimeStatus, 1000);

        // 监听时间配置变化
        $('#morningStart, #morningEnd, #afternoonStart, #afternoonEnd, #enableTimeControl').on('change', function() {
            updateTimeStatus();
            // 保存时间配置
            saveTimeConfig();
        });

        // 监听筛选器变化
        $('#showOnlyGEM, #showOnlyKCB, #showOnlyMain, #showOnlyBJ, #showOnlyST').on('change', function() {
            updateFilterStats();
        });

        // 监听关注设置变化
        $('#focusStocks, #focusGainian').on('input', function() {
            const focusStocks = $('#focusStocks').val();
            const focusGainian = $('#focusGainian').val();
            updateFocusStatus(focusStocks, focusGainian);
        });

        // 初始化状态显示
        updateFilterStats();
        updateFocusStatus($('#focusStocks').val(), $('#focusGainian').val());

    });

    // 初始化图表
    function initCharts() {
        // 板块分布图表
        const sectorCtx = document.getElementById('sectorChart').getContext('2d');
        sectorChart = new Chart(sectorCtx, {
            type: 'doughnut',
            data: {
                labels: ['主板', '创业板', '科创板', '北交所', 'ST股票'],
                datasets: [{
                    data: [0, 0, 0, 0, 0],
                    backgroundColor: [
                        '#667eea',
                        '#764ba2',
                        '#f093fb',
                        '#f5576c',
                        '#4facfe'
                    ],
                    borderWidth: 1,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '板块分布'
                    },
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });

        // 股票类型图表
        const typeCtx = document.getElementById('typeChart').getContext('2d');
        typeChart = new Chart(typeCtx, {
            type: 'bar',
            data: {
                labels: ['正常', '重点关注', '新出现', '洗盘', '连续'],
                datasets: [{
                    label: '股票数量',
                    data: [0, 0, 0, 0, 0],
                    backgroundColor: [
                        'rgba(102, 126, 234, 0.7)',
                        'rgba(255, 152, 0, 0.7)',
                        'rgba(76, 175, 80, 0.7)',
                        'rgba(33, 150, 243, 0.7)',
                        'rgba(233, 30, 99, 0.7)'
                    ],
                    borderColor: [
                        '#667eea',
                        '#ff9800',
                        '#4caf50',
                        '#2196f3',
                        '#e91e63'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '股票类型分布'
                    },
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }

    // 更新统计数据和图表
    function updateStatsAndCharts(stocks) {
        // 统计各类型股票数量
        const stats = {
            total: stocks.length,
            main: 0,      // 主板
            gem: 0,       // 创业板
            kcb: 0,       // 科创板
            bj: 0,        // 北交所
            st: 0,        // ST股票
            type0: 0,     // 正常
            type1: 0,     // 重点关注
            type2: 0,     // 新出现
            type3: 0,     // 洗盘
            type4: 0      // 连续
        };

        stocks.forEach(stock => {
            // 统计板块
            if (stock.code.startsWith('60') || (stock.code.startsWith('00') && !stock.code.startsWith('002'))) {
                stats.main++;
            } else if (stock.code.startsWith('30')) {
                stats.gem++;
            } else if (stock.code.startsWith('688')) {
                stats.kcb++;
            } else if (stock.code.startsWith('8') || stock.code.startsWith('43')) {
                stats.bj++;
            }

            if (stock.name && stock.name.includes('ST')) {
                stats.st++;
            }

            // 统计类型
            const type = stock.type || 0;
            stats[`type${type}`]++;
        });

        // 更新统计卡片
        $('#totalStockCount').text(stats.total);
        $('#matchStockCount').text(stats.total);
        $('#focusStockCount').text(stats.type1);
        $('#newStockCount').text(stats.type2);

        // 更新板块分布图表
        sectorChart.data.datasets[0].data = [
            stats.main,
            stats.gem,
            stats.kcb,
            stats.bj,
            stats.st
        ];
        sectorChart.update();

        // 更新股票类型图表
        typeChart.data.datasets[0].data = [
            stats.type0,
            stats.type1,
            stats.type2,
            stats.type3,
            stats.type4
        ];
        typeChart.update();
    }

    // 初始化统计面板折叠功能
    function initStatsCollapse() {
        const statsCollapse = $('#statsCollapse');
        const collapseToggle = $('a[href="#statsCollapse"]');
        const collapseText = collapseToggle.find('.collapse-text');

        // 监听折叠状态变化
        statsCollapse.on('shown.bs.collapse', function () {
            collapseText.text('收起');
            if (sectorChart) sectorChart.resize();
            if (typeChart) typeChart.resize();
        });

        statsCollapse.on('hidden.bs.collapse', function () {
            collapseText.text('展开');
        });

        // 初始状态检查
        if (statsCollapse.hasClass('show')) {
            collapseText.text('收起');
        } else {
            collapseText.text('展开');
        }
    }

    // 初始化控制面板折叠功能
    function initControlsCollapse() {
        const controlsCollapse = $('#inputControlsCollapse');
        const collapseToggle = $('a[href="#inputControlsCollapse"]');
        const collapseText = collapseToggle.find('.collapse-text');

        // 监听折叠状态变化
        controlsCollapse.on('shown.bs.collapse', function () {
            collapseText.text('收起');
        });

        controlsCollapse.on('hidden.bs.collapse', function () {
            collapseText.text('展开');
        });

        // 初始状态检查
        if (controlsCollapse.hasClass('show')) {
            collapseText.text('收起');
        } else {
            collapseText.text('展开');
        }
    }

    // 全屏功能
    let isFullscreen = false;
    let originalParent = null;
    let originalNextSibling = null;

    function initFullscreenFeature() {
        const fullscreenBtn = $('#fullscreenBtn');
        const exitFullscreenBtn = $('#exitFullscreenBtn');
        const tableContainer = $('#tableContainer');

        // 全屏按钮点击事件
        fullscreenBtn.on('click', function() {
            enterFullscreen();
        });

        // 退出全屏按钮点击事件
        exitFullscreenBtn.on('click', function() {
            exitFullscreen();
        });

        // ESC键退出全屏
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && isFullscreen) {
                exitFullscreen();
            }
        });
    }

    function enterFullscreen() {
        const tableContainer = $('#tableContainer');
        const fullscreenBtn = $('#fullscreenBtn');
        const exitFullscreenBtn = $('#exitFullscreenBtn');

        if (isFullscreen) return;

        // 保存原始位置信息
        originalParent = tableContainer.parent();
        originalNextSibling = tableContainer.next();

        // 添加全屏样式
        tableContainer.addClass('fullscreen');

        // 移动到body下
        $('body').append(tableContainer);

        // 显示退出按钮，隐藏全屏按钮
        exitFullscreenBtn.show();
        fullscreenBtn.hide();

        // 隐藏body滚动条
        $('body').css('overflow', 'hidden');

        isFullscreen = true;

        // 触发窗口resize事件
        setTimeout(() => {
            $(window).trigger('resize');
        }, 100);
    }

    function exitFullscreen() {
        const tableContainer = $('#tableContainer');
        const fullscreenBtn = $('#fullscreenBtn');
        const exitFullscreenBtn = $('#exitFullscreenBtn');

        if (!isFullscreen) return;

        // 移除全屏样式
        tableContainer.removeClass('fullscreen');

        // 恢复到原始位置
        if (originalNextSibling.length > 0) {
            originalNextSibling.before(tableContainer);
        } else {
            originalParent.append(tableContainer);
        }

        // 隐藏退出按钮，显示全屏按钮
        exitFullscreenBtn.hide();
        fullscreenBtn.show();

        // 恢复body滚动条
        $('body').css('overflow', '');

        isFullscreen = false;

        // 触发窗口resize事件
        setTimeout(() => {
            $(window).trigger('resize');
        }, 100);
    }

    // 监听浏览器全屏状态变化
    function handleFullscreenChange() {
        if (!document.fullscreenElement && !document.webkitFullscreenElement &&
            !document.mozFullScreenElement && !document.msFullscreenElement) {
            if (isFullscreen) {
                exitFullscreen();
            }
        }
    }

    // 绑定浏览器全屏事件监听
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
    document.addEventListener('mozfullscreenchange', handleFullscreenChange);
    document.addEventListener('MSFullscreenChange', handleFullscreenChange);

    // 时间段检查相关函数
    function isInMonitoringTime() {
        if (!$('#enableTimeControl').prop('checked')) {
            return true; // 如果未启用时间控制，总是允许监控
        }

        const now = new Date();
        const currentTime = now.getHours() * 60 + now.getMinutes(); // 转换为分钟数

        // 获取配置的时间段（转换为分钟数）
        const morningStart = timeToMinutes($('#morningStart').val());
        const morningEnd = timeToMinutes($('#morningEnd').val());
        const afternoonStart = timeToMinutes($('#afternoonStart').val());
        const afternoonEnd = timeToMinutes($('#afternoonEnd').val());

        // 检查是否在上午时段或下午时段内
        const inMorning = currentTime >= morningStart && currentTime <= morningEnd;
        const inAfternoon = currentTime >= afternoonStart && currentTime <= afternoonEnd;

        return inMorning || inAfternoon;
    }

    function timeToMinutes(timeStr) {
        if (!timeStr) return 0;
        const [hours, minutes] = timeStr.split(':').map(Number);
        return hours * 60 + minutes;
    }

    function minutesToTime(minutes) {
        const hours = Math.floor(minutes / 60);
        const mins = minutes % 60;
        return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`;
    }

    function updateTimeStatus() {
        const now = new Date();
        const currentTimeStr = now.toLocaleTimeString('zh-CN', { hour12: false });
        $('#currentTime').text(currentTimeStr);

        const isInTime = isInMonitoringTime();
        const timeControlStatus = $('#timeControlStatus');
        const gainianTimeControlStatus = $('#gainianTimeControlStatus');

        if (!$('#enableTimeControl').prop('checked')) {
            timeControlStatus.text('已禁用时间控制').removeClass('text-success text-danger').addClass('text-warning');
            gainianTimeControlStatus.text('已禁用时间控制').removeClass('text-success text-danger').addClass('text-warning');
        } else if (isInTime) {
            timeControlStatus.text('时间段内').removeClass('text-danger text-warning').addClass('text-success');
            gainianTimeControlStatus.text('时间段内').removeClass('text-success text-warning').addClass('text-success');
        } else {
            timeControlStatus.text('时间段外').removeClass('text-success text-warning').addClass('text-danger');
            gainianTimeControlStatus.text('时间段外').removeClass('text-success text-warning').addClass('text-danger');
        }
    }

    function saveTimeConfig() {
        const timeConfig = {
            morningStart: $('#morningStart').val(),
            morningEnd: $('#morningEnd').val(),
            afternoonStart: $('#afternoonStart').val(),
            afternoonEnd: $('#afternoonEnd').val(),
            enableTimeControl: $('#enableTimeControl').prop('checked')
        };

        $.ajax({
            url: '/sysinfo/updateTimeConfig',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(timeConfig),
            success: function (response) {
                console.log('时间配置保存成功');
            },
            error: function (error) {
                console.error('时间配置保存失败:', error);
            }
        });
    }

    function updateSys() {
        var searchKeyword = $('#iwencaiKeyword').val();
        var gainianKeyword = $('#gainianKeyword').val();
        var focusStocks = $('#focusStocks').val();
        var allOptional = $('#allOptional').val(); //自选的票
        var focusGainian = $('#focusGainian').val();

        focusStocks=(focusStocks ? focusStocks.split('\n').join(',') : '');

        // 更新关注状态显示
        updateFocusStatus(focusStocks, focusGainian);

        $.ajax({
            url: '/sysinfo/update',
            method: 'GET',
            data: {
                searchKeyword: searchKeyword,
                gainianKeyword: gainianKeyword,
                focusStocks: focusStocks,
                allOptional: allOptional,
                focusGainian: focusGainian
            },
            success: function (response) {
                // 成功处理
            },
            error: function (xhr, status, error) {
                console.error('概念查询失败:', error);
            }
        });
    }

    // 更新关注状态显示
    function updateFocusStatus(focusStocks, focusGainian) {
        const focusStatus = $('#focusStatus');
        if (focusStocks || focusGainian) {
            focusStatus.text('已设置').removeClass('bg-secondary').addClass('bg-success');
        } else {
            focusStatus.text('未设置').removeClass('bg-success').addClass('bg-secondary');
        }
    }

    // 更新筛选统计
    function updateFilterStats() {
        const activeFilters = [];
        if ($('#showOnlyGEM').prop('checked')) activeFilters.push('创业板');
        if ($('#showOnlyKCB').prop('checked')) activeFilters.push('科创板');
        if ($('#showOnlyMain').prop('checked')) activeFilters.push('主板');
        if ($('#showOnlyBJ').prop('checked')) activeFilters.push('北交所');
        if ($('#showOnlyST').prop('checked')) activeFilters.push('ST股票');

        const filterStats = $('#filterStats');
        if (activeFilters.length === 0) {
            filterStats.text('显示全部');
        } else {
            filterStats.text(`筛选: ${activeFilters.join(', ')}`);
        }
    }

    function processSpecialString() {
        var str=$('#iwencaiKeyword').val();
        str = str.replace(/(?<=\})的/g, '');
        let processedStr = str.replace(/\{[^}]*\}/g, '');
        $('#iwencaiKeyword').val(processedStr);
    }

    function checkfocusStocks() {
        var str=$('#focusStocks').val();
        let processedStr = str.split(',').join('\n');
        $('#focusStocks').val(processedStr);
    }

    function checkallOptional() {
        var str=$('#allOptional').val();
        let processedStr = str.split('\n')
            .map(line => line.trim())
            .map(line => line.length==8 ? line.slice(-6) : line)
            .join(',');
        $('#allOptional').val(processedStr);
    }

    // 将函数添加到window对象，使其成为全局函数
    window.isInMonitoringTime = isInMonitoringTime;

    // 功能函数
    function toggleMonitoring() {
        console.log('监控状态切换');
    }

    function toggleGainianMonitoring() {
        console.log('概念监控状态切换');
    }

    function openReduIwencai() {
        console.log('打开热榜');
    }

    function openIwencaiKey(keyword) {
        console.log('打开问财关键词:', keyword);
    }

    function openIwencai() {
        console.log('打开问财');
    }

    function openGainianIwencai() {
        console.log('打开概念问财');
    }


    // 1. 定义刷新间隔（270000毫秒）
    const refreshInterval = 270000;
    // const refreshInterval = 10000;
    let refreshTimer = null; // 定时器实例（全局/闭包存储）

    // 2. 启动刷新的函数
    function startRefresh() {
        // 先清除已有定时器（避免重复启动）
        if (refreshTimer) clearInterval(refreshTimer);

        // 启动新定时器
        refreshTimer = setInterval(() => {
            // 仅在页面可见时刷新（优化体验）
            if (document.visibilityState === 'visible') {
                location.href = location.href; // 强制刷新（无缓存）
            }
        }, refreshInterval);

        console.log(`定时刷新已启动，间隔：4分30秒`);
    }

    // 3. 停止刷新的函数（可通过按钮调用）
    function stopRefresh() {
        if (refreshTimer) {
            clearInterval(refreshTimer);
            refreshTimer = null;
            console.log(`定时刷新已停止`);
        }
    }

    // 4. 页面加载完成后自动启动刷新
    window.addEventListener('load', startRefresh);

    // 5. 可选：页面隐藏时暂停刷新，显示时恢复刷新
    document.addEventListener('visibilitychange', () => {
        // if (document.visibilityState === 'visible' && !refreshTimer) {
        //     startRefresh(); // 页面显示且无定时器时，恢复刷新
        // } else if (document.visibilityState === 'hidden' && refreshTimer) {
        //     clearInterval(refreshTimer); // 页面隐藏时，暂停刷新
        //     refreshTimer = null;
        // }
    });

    // 示例：通过按钮手动停止（需配合HTML）
    // <button onclick="stopRefresh()">停止自动刷新</button>
    // <button onclick="startRefresh()">恢复自动刷新</button>
</script>
<script src="/js/stock.js"></script>

</body>
</html>
